﻿using System.Data.Services;
using System.Net;

namespace AstoriaPlus
{
	/// <summary>
	/// Extensions to <see cref="IPipelineContext"/>.
	/// </summary>
	public static class PipelineContextExtensions
	{
		/// <summary>
		/// Gets the entry of the given type <typeparamref name="T"/> or throws a <see cref="DataServiceException"/> exception.
		/// </summary>
		/// <typeparam name="T">Type of entry to retrieve from the context</typeparam>
		/// <param name="context">The context to retrieve the entry from.</param>
		/// <param name="statusCode">The status code to set on the thrown <see cref="System.Data.Services.DataServiceException"/>.</param>
		/// <param name="messageOrFormat">The error message in case the entry is not found, or a format string to use together with the optional <paramref name="args"/>.</param>
		/// <param name="args">The format arguments for <paramref name="messageOrFormat"/>.</param>
		/// <returns>The entry or throws an exception if not found.</returns>
		public static T GetOrThrow<T>(this IPipelineContext context, HttpStatusCode statusCode, string messageOrFormat, params object[] args)
		{
			var value = context.Get<T>();
			if (value == null)
				statusCode.Throw(messageOrFormat, args);

			return value;
		}
	}
}
